package cn.cht.service.impl;


import cn.cht.pojo.User;
import cn.cht.repository.UserRepository;
import cn.cht.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import org.springframework.util.StringUtils;

import java.sql.Date;
import java.time.Instant;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository repository;

    @Override
    public User register(String email, String password) {

        if (repository.findAllByEmail(email).size()==0) {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            user.setCreateTime(Date.from(Instant.now()));
            return repository.save(user);
        } else {
            return null;
        }
    }

    @Override
    public User isRegistered(String email) {
        if (StringUtils.isEmpty(email)) {
            return null;
        }
        User user = new User();
        user.setEmail(email);
        return repository.findOne(Example.of(user)).orElse(null);
    }

    @Override
    public User login(String email, String password) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        return repository.findOne(Example.of(user)).orElse(null);
    }
}
